// miniprogram/pages/poetry/oldbook/detail/detail.js
const poetry_db = wx.cloud.database().collection("poetry")
const $ = wx.cloud.database().command

Page({
  data: {
    bookName: '',
    curIndex: 0,
    hasPre: false,
    hasNext: false,
    chapterMenu: [],
    chapterFunc: {
      x: 70,
      y: 250
    },
    showChapterMenu: false
  },
  onLoad: function (options) {
    console.log(options)
    var curIndex = decodeURIComponent(options.curIndex)
    var bookName = decodeURIComponent(options.bookName)
    wx.setNavigationBarTitle({
      title: bookName
    })
    //获取目录数据
    poetry_db.where({
      bookName: bookName,
      year: $.exists(true)
    }).get({
      success: (res) => {
        console.log(res)
        var oldBook = res.data[0]
        this.setData({
          bookName: bookName,
          chapterMenu: oldBook.chapters
        })
        this.getChapterInfo(curIndex)
      }
    })
  },
  onShareAppMessage: function () {

  },
  //获取目录下的内容
  getChapterInfo(index) {
    // console.log("getChapterInfo", index, typeof (index))
    var bookName = this.data.bookName
    var chapterMenu = this.data.chapterMenu
    var chapter = chapterMenu[index]
    // console.log(chapter)
    poetry_db.where({
      bookName: bookName,
      chapterName: chapter
    }).get({
      success: (res) => {
        console.log(res)
        var bookInfo = res.data[0]
        var curIndex = parseInt(index)
        //是否有上一页或者下一页
        var hasPre = true
        if (curIndex == 0)
          hasPre = false
        var hasNext = true
        if (curIndex == chapterMenu.length - 1)
          hasNext = false
        this.setData({
          bookInfo: bookInfo,
          curIndex: curIndex,
          hasPre: hasPre,
          hasNext: hasNext
        })
        this.backTop()
      }
    })
  },
  //上一章或下一章点击监听
  onChapterClick(e) {
    // console.log(e)
    var curIndex = this.data.curIndex
    var flag = e.currentTarget.dataset.flag
    var mIndex = curIndex - 1
    if (flag == "next")
      mIndex = curIndex + 1
    this.getChapterInfo(mIndex)
  },
  //章节目录按钮点击监听
  showChapterMenuClick(e) {
    this.setData({
      showChapterMenu: true
    })
  },
  //背景点击监听
  onMenuEmptyClick() {
    setTimeout(() => {
      this.setData({
        showChapterMenu: false
      })
    }, 300)
  },
  //章节item点击监听
  onChapterItemClick(e) {
    console.log(e)
    var itemIndex = e.currentTarget.dataset.index
    this.getChapterInfo(itemIndex)
    this.onMenuEmptyClick()
  },
  // 滚动到顶部
  backTop() {
    // 控制滚动
    wx.pageScrollTo({
      scrollTop: 0
    })
  }
})